package middleware

import (
	"encoding/gob"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type LoginMiddlewareBuilder struct {
	paths []string
}

func NewLoginMiddlewareBuilder() *LoginMiddlewareBuilder {
	return &LoginMiddlewareBuilder{
		paths: []string{},
	}
}

func (mw *LoginMiddlewareBuilder) Ignore(path string) *LoginMiddlewareBuilder {
	mw.paths = append(mw.paths, path)
	return mw
}

// 登录状态检查
func (mw *LoginMiddlewareBuilder) LoginCheck() gin.HandlerFunc {
	gob.Register(time.Now())
	return func(ctx *gin.Context) {
		for _, path := range mw.paths {
			if ctx.Request.URL.Path == path {
				return
			}
		}

		sess := sessions.Default(ctx)
		sess.Options(sessions.Options{
			MaxAge: 60,
		})
		id := sess.Get("userId")
		if id == nil {
			//未登录状态
			ctx.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		//登录状态刷新
		sess.Set("userId", id)
		updateTime := sess.Get("update_time")
		if updateTime == nil {
			//第一次登录,刷新一下
			sess.Set("update_time", time.Now())
			if err := sess.Save(); err != nil {
				panic(err)
			}
			return
		}

		//转换类型为time.Time
		updateTimeVal, ok := updateTime.(time.Time)
		if !ok {
			ctx.AbortWithStatus(http.StatusInternalServerError)
			return
		}

		//距离上次刷新时间超过10秒，刷新一下
		if time.Now().Sub(updateTimeVal) > time.Second*10 {
			sess.Set("update_time", time.Now())
			if err := sess.Save(); err != nil {
				panic(err)
			}
		}

	}
}
